package com.gxa.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.wf.captcha.SpecCaptcha;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*
图片验证码接口
1、导入依赖easy-captcha1.6.2
2、创建SpecCaptcha对象
 */
@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建SpecCaptcha对象
        SpecCaptcha specCaptcha= new SpecCaptcha(120,40,4);//宽、高、验证码数字/字母数量
        //获取验证码的值
        String verCode = specCaptcha.text().toLowerCase();
        //存储在服务器的session
        HttpSession session = request.getSession();
        session.setAttribute("serverCode",verCode);
        //利用工具生成图片验证码后，用流方式回写到login.html页面
        Map map = new HashMap();
        map.put("image",specCaptcha.toBase64());//图片 使用Base64编码把图片对象转成图片地址返回
        //设置响应的编码
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(map));

    }
}
